<template>
    <div>
        <el-form :model="form" class="demo-form-inline">
            <el-form-item label="">
                <el-input v-model="form.username" placeholder="请输入用户名" clearable size="large" :prefix-icon="User" />
            </el-form-item>
            <el-form-item label="">
                <el-input type="password" v-model="form.password" placeholder="请输入用密码" clearable size="large"
                    :prefix-icon="Lock" show-password />
            </el-form-item>
            <el-form-item label="">
                <div style="display: flex;">
                    <el-input v-model="form.captcha" placeholder="请输入验证码" clearable size="large"
                        :prefix-icon="CircleCheck" />
                    <el-image :src="captchas.url" style="margin-left: 10px; width: 100%; height: 50px; cursor: pointer;"
                        @click="getCode" />
                </div>
            </el-form-item>
            <el-form-item label="">
                <el-button type="primary" size="large" style="flex:1;width: 100%;" @click="submitForm">登录</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script setup>
import { getCaptcha, loginByJson } from '@/api/login.js'
import { User, Lock, CircleCheck } from '@element-plus/icons-vue'
import { Encrypt } from '@/utils/aes.js'
import { useUserStore } from '@/store/user'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
let userStore = useUserStore()
let router = useRouter()
let form = reactive({
    username: 'admin',
    password: "abc123456",
    captcha: ''
})

let captchas = reactive({
    url: "",
    key: ""
})

const getCode = async () => {
    captchas.key = new Date().getTime().toString()
    const res = await getCaptcha({ key: captchas.key })
    let blob = new Blob([res], { type: 'application/vnd.ms-excel' });
    let imgUrl = URL.createObjectURL(blob);
    captchas.url = imgUrl;
}
const submitForm = async () => {
    let { key } = captchas
    let { username, password, captcha } = form;

    const res = await loginByJson({ username: Encrypt(username), password: Encrypt(password), captcha, key })

    if (res.code != 200) {
        return
    }
    localStorage.setItem('TOKEN', res.data);
    userStore.getUserInfo()
    router.push('/')
}
onMounted(() => {
    getCode()
})
</script>

<style lang="scss" scoped></style>